﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Threading.Tasks;

namespace Anay.TaskScheduling.Common
{
    /// <summary>
    /// 初始化一个调度器，让它一直运行
    /// </summary>
    public class AppQuartz
    {
        public AppQuartz()
        {




        }

        public async Task RunProgram()
        {
            try
            {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                IScheduler scheduler = await new StdSchedulerFactory(props).GetScheduler();
                await scheduler.Start();
                IJobDetail jobDetail = JobBuilder.Create<AppQuartzJob>()
                                                     .WithIdentity(new JobKey("Job", "Group"))
                                                     .Build();
                ITrigger trigger = TriggerBuilder.Create()
                                                 .WithIdentity(new TriggerKey("Job", "Group"))
                                                 .StartNow()
                                                 .WithSimpleSchedule(x => x
                                                    .WithIntervalInSeconds(60)
                                                     .RepeatForever())
                                                 .Build();
                await scheduler.ScheduleJob(jobDetail, trigger);
                //await Task.Delay(TimeSpan.FromSeconds(60));
                //await scheduler.Shutdown();
            }
            catch (System.Exception ex)
            {

                throw;
            }
        }
    }

    public class AppQuartzJob : IJob
    {
        public static bool isLock = false;
        public static object lock_obj = new object();

        public async Task Execute(IJobExecutionContext context)
        {
            await Task.Run(() =>
            {
                while (isLock)
                {
                    System.Threading.Thread.Sleep(3000);
                }
                //用于线程安全
                lock (lock_obj)
                {
                    isLock = true;
                }
                try
                {
                    QuartzHelper QuartzHelper = new QuartzHelper();
                    WriteLog("-----" + DateTime.Now.ToString("HH:mm:ss") + "检查开始:\n");
                    if (QuartzHelper.IsStarted())
                    {
                        WriteLog("结果：正常\n");
                    }
                    else
                    {
                        WriteLog("结果：已关闭，自动重启启动\n");
                        QuartzHelper.Start();
                        QuartzHelper.ResumeAll();
                    }
                    WriteLog("-----" + DateTime.Now.ToString("HH:mm:ss") + "检查结束:\r\n");
                }
                catch (Exception ex)
                {
                    Anay.Logging.LogHelper.Write("内部调度器出错：" + ex.Message + "\r\n" + ex.StackTrace);
                }
                finally
                {

                    isLock = false;
                }


            });


        }

        private void WriteLog(string msg)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"/Log/QuartzState/"; //+ DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path += "QuartzState" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
            FileInfo file = new FileInfo(path);
            if (!file.Exists)
            {

                FileStream fs;
                fs = File.Create(path);
                fs.Close();
            }

            using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(msg);
                }
            }
        }
    }

    public class HelloJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            await Console.Out.WriteLineAsync("Greetings from HelloJob!");
        }
    }
}
